import React, { useState, useEffect } from 'react'
import { NavBar, Image, Collapse, Toast, Ellipsis, Space, Swiper } from 'antd-mobile'
import { getIndexImage, getIndexWorks, getIndexBlog } from '../../api'
import Bottom from '../../components/Bottom'

import './index.css'

export default function Home() {
  const [show, setShow] = useState(false)
  const [imageArr, setImageArr] = useState([])
  const [worksArr, setWorksArr] = useState([])
  const [blogArr, setBlogArr] = useState([])
  useEffect(()=>{
    homeData()
  },[])

  async function homeData(){
    try {
      const image = await getIndexImage()
      const works = await getIndexWorks()
      const blog = await getIndexBlog()
      setImageArr([...image])
      setWorksArr([...works])
      setBlogArr([...blog])
      setShow(true)
    } catch (error) {
      Toast.show({
        content: error.message,
        icon: 'fail'
      })
    }
  }

  function awaitImg(e){
    e.target.className='banner-img-show'
  }

  const items = imageArr.map((imageObj) => {
    return <Swiper.Item key={imageObj.id}>
        <div className='slideshow'>
        <Image
          className='img-item'
          alt="banner"
          lazy
          src={imageObj.url}
          />
        </div>
        
    </Swiper.Item>
  })

  const collapsePanelHtml = blogArr.map((blogObj)=>{
    return <Collapse.Panel key={blogObj.id} title={<Ellipsis className='blogtitle' direction='end' content={blogObj.title} />}>{blogObj.context}</Collapse.Panel>
  })

  const workListHtml = worksArr.map((workObj)=>{
    const {id, src, name, time} = workObj
    return <li key={id}>
      <div className='image'>
        <img className='banner-img-hide' src={src} alt="img" onLoad={awaitImg} />
      </div>
      <div className='describe'>
        <span><Ellipsis direction='end' rows={2} content={name} /></span>
        <span>{time}</span>
      </div>
    </li>
  })

  return (
    <div id='home'>
      <NavBar className='navbar' back={null}>首页</NavBar>
      {
        show && <Space direction='vertical' block>
          <Swiper
            loop
            autoplay
            autoplayInterval="5000"
            defaultIndex={0}
          >
              {items} 
          </Swiper>
        </Space>
      }
      
      <div className='works'>
        <ul>
          {workListHtml}
        </ul>
      </div>
      <div className='blog'>
        <Collapse accordion>
          {collapsePanelHtml}
        </Collapse>
      </div>
      <Bottom />
    </div>
  )
}
